package com.gitee.apecome.core.remote.consumer;

import com.gitee.apecome.core.remote.ApeRpcFactory;
import com.gitee.apecome.core.remote.ApeRpcFutureResponse;
import com.gitee.apecome.core.remote.bean.ApeRpcRequest;
import com.gitee.apecome.core.remote.bean.ApeRpcResponse;
import com.gitee.apecome.core.remote.net.netty.client.Client;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang.StringUtils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Objects;
import java.util.UUID;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class ApeRpcReferenceBean {

    private ApeRpcFactory factory;

    private Class<?> itface;

    private String version;

    private String address;

    private String accessToken;


    public void validate() {
        if (Objects.isNull(itface)) {
            throw new RuntimeException("interface is Null");
        }

        if (!itface.isInterface()) {
            throw new RuntimeException("validate it must be interface");
        }

        if (Objects.isNull(address)) {
            throw new RuntimeException("interface is Null");
        }

        factory = ApeRpcFactory.newInstance();
    }


    public Object getProxyObject() {
        validate();
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{itface}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                ApeRpcRequest request = ApeRpcRequest.builder()
                        .className(itface.getName())
                        .methodName(method.getName())
                        .parameterTypes(method.getParameterTypes())
                        .parameters(args)
                        .requestId(UUID.randomUUID().toString())
                        .version(version)
                        .accessToken(accessToken)
                        .build();
                System.out.println(request);
                try {
                    ApeRpcFutureResponse futureResponse = new ApeRpcFutureResponse(factory, request);
                    String[] split = address.split(":");
                    Client connection = factory.getConnection(split[0], Integer.parseInt(split[1]));
                    connection.asyncRequest(request);
                    ApeRpcResponse response = futureResponse.get();
                    if (StringUtils.isNotEmpty(response.getErrorMsg())) {
                        throw new RuntimeException(response.getErrorMsg());
                    }
                    return response.getResult();
                } finally {
                    factory.removeFuture(request.getRequestId());
                }
            }
        });
    }
}
